package com.stefanhermann.particlestest;

import java.util.Random;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;

public class ParticleEmitter {

	public int PARTICLECOUNT = 50;
	private Particle particles[];
	Paint particlePaint = new Paint();
	long lastTime;
	long currentTime;
	private boolean initialized = false;
	private float AX = 0f;
	private float AY = 60f; // y-acceleration
	private float velTolerance = 0.6f;
	private Vec2 position = new Vec2();
	private Vec2 initialVelocity = new Vec2();
	private float angleTolerance;
	private Vec2 tempVelocity;

	public ParticleEmitter() {
		particles = new Particle[PARTICLECOUNT];
		currentTime = System.currentTimeMillis();
		particlePaint.setAntiAlias(true);
		particlePaint.setColor(Color.GREEN);
	}

	public void setPosition(float x, float y) {
		position.set(x, y);
	}

	public void setVelocity(float x, float y, float tolerance) {
		initialVelocity.set(x, y);
		angleTolerance = tolerance;
	}

	public void initialize() {
		Random r = new Random();
		for (int i = 0; i < PARTICLECOUNT; i++) {
			tempVelocity = initialVelocity.cpy();
			tempVelocity.rotate(angleTolerance * (r.nextFloat() - 0.5f));
			particles[i] = new Particle(position.x, position.y);
			particles[i].vX = tempVelocity.x - (tempVelocity.x * r.nextFloat() * velTolerance);
			particles[i].vY = tempVelocity.y - (tempVelocity.y * r.nextFloat() * velTolerance);
		}

		initialized = true;
	}

	public void update(Canvas canvas) {
		Random r = new Random(); ///////<-----------
		if (initialized) {
			lastTime = currentTime;
			currentTime = System.currentTimeMillis();
			float dTime = (lastTime - currentTime) / 1000f;

			for (Particle cParticle : particles) {
				// Accelerate and move
				if (cParticle.y <= 610) {
					cParticle.vX += dTime * AX;
					cParticle.x += dTime * cParticle.vX;
					cParticle.vY += dTime * AY;
					cParticle.y += dTime * cParticle.vY;

					canvas.drawCircle(cParticle.x, cParticle.y, 5, particlePaint);
				} else {
					tempVelocity = initialVelocity.cpy();
					tempVelocity.rotate(angleTolerance * (r.nextFloat() - 0.5f));
					cParticle.x = position.x;
					cParticle.y = position.y;
					cParticle.vX = tempVelocity.x - (tempVelocity.x * r.nextFloat() * velTolerance);
					cParticle.vY = tempVelocity.y - (tempVelocity.y * r.nextFloat() * velTolerance);					
//					cParticle.vY = 0;
//					cParticle.y = 0;
				}
			}
		}
	}
}
